<template>
  <div class="home-page">
    <!-- 背景层 -->
    <div class="hero-section">
      <img
        src="@/assets/background.jpg"
        alt="背景图"
        class="background-image"
      />

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form @submit.prevent="handleSearch">
          <el-row :gutter="16" class="search-row">
            <!-- 标题/小区 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" class="search-item">
              <el-input
                v-model="searchParams.title"
                placeholder="标题/小区"
                clearable
              />
            </el-col>

            <!-- 城市选择 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" class="search-item">
              <el-select
                v-model="searchParams.city"
                placeholder="选择城市"
                clearable
              >
                <el-option
                  v-for="city in cityOptions"
                  :key="city"
                  :label="city"
                  :value="city"
                />
              </el-select>
            </el-col>

            <!-- 租赁类型 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" class="search-item">
              <el-select
                v-model="searchParams.rentType"
                placeholder="租赁类型"
                clearable
              >
                <el-option label="整租" value="whole" />
                <el-option label="合租" value="share" />
              </el-select>
            </el-col>

            <!-- 金额范围 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" class="search-item">
              <div class="rent-range">
                <el-input-number
                  v-model="searchParams.minRent"
                  :min="0"
                  placeholder="最低"
                  controls-position="right"
                  class="rent-input"
                />
                <span class="separator">-</span>
                <el-input-number
                  v-model="searchParams.maxRent"
                  :min="searchParams.minRent || 0"
                  placeholder="最高"
                  controls-position="right"
                  class="rent-input"
                />
              </div>
            </el-col>

            <!-- 搜索按钮 -->
            <el-col
              :xs="24"
              :sm="24"
              :md="8"
              :lg="6"
              class="search-item btn-container"
            >
              <div class="btn-wrapper">
                <el-button
                  type="primary"
                  icon="Search"
                  native-type="submit"
                  class="search-btn"
                >
                  搜索
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 房源列表区域 -->
    <div class="house-list-section">
      <div class="container">
        <!-- 标题和排序 -->
        <div class="list-header">
          <h2 class="section-title">精选房源</h2>
          <div class="sort-controls">
            <span class="total-count">总记录数 {{ pagination.total }}</span>
            <el-button-group>
              <el-button
                :type="sortField === 'monthRent' ? 'primary' : ''"
                @click="handleSort('monthRent')"
              >
                价格排序 {{ sortOrder === "asc" ? "↑" : "↓" }}
              </el-button>
              <el-button
                :type="sortField === 'createTime' ? 'primary' : ''"
                @click="handleSort('createTime')"
              >
                最新排序 {{ sortOrder === "asc" ? "↑" : "↓" }}
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 分页控件 -->
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :page-sizes="[10, 20, 30]"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />

        <!-- 房源列表 -->
        <div class="house-grid">
          <div
            v-for="house in houses"
            :key="house.id"
            class="house-card"
            @click="handleViewDetail(house.id)"
          >
            <el-carousel
              v-if="house.houseImageList?.length"
              indicator-position="none"
              height="200px"
            >
              <el-carousel-item
                v-for="(img, index) in house.houseImageList"
                :key="index"
              >
                <img
                  :src="img"
                  class="house-image"
                  @error="handleImageError($event, house)"
                />
              </el-carousel-item>
            </el-carousel>
            <div v-else class="image-placeholder">
              <el-icon :size="40"><Picture /></el-icon>
            </div>

            <div class="card-content">
              <h3 class="house-title">{{ house.title }}</h3>
              <div class="house-tags">
                <el-tag type="info" size="small">{{ house.city }}</el-tag>
                <el-tag
                  :type="house.rentType === 'whole' ? 'success' : 'warning'"
                  size="small"
                >
                  {{ house.rentType === "whole" ? "整租" : "合租" }}
                </el-tag>
              </div>
              <div class="house-info">
                <div class="info-item">
                  <el-icon><OfficeBuilding /></el-icon>
                  {{ house.area }}㎡ | {{ house.bedroom }}室{{
                    house.livingRoom
                  }}厅
                </div>
                <div class="info-item">
                  <el-icon><Location /></el-icon>
                  {{ house.address }}
                </div>
              </div>
              <div class="price-section">
                <span class="price">{{ house.monthRent }}</span>
                <span class="unit">元/月</span>
                <el-tag
                  v-if="house.status === 2"
                  type="danger"
                  size="small"
                  class="status-tag"
                >
                  已出租
                </el-tag>
              </div>
              <!-- 收藏按钮 -->
              <div class="favorite-button" v-if="isTenant">
                <el-tooltip
                  :content="house.isFavorite ? '取消收藏' : '收藏房源'"
                >
                  <el-icon
                    :size="24"
                    :class="[
                      'favorite-icon',
                      {
                        active: house.isFavorite,
                        loading: house.loading,
                      },
                    ]"
                    @click.stop="handleFavorite(house.id)"
                  >
                    <StarFilled v-if="house.isFavorite" />
                    <Star v-else />
                  </el-icon>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>

        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :page-sizes="[8, 16, 32]"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import {
  Picture,
  OfficeBuilding,
  Location,
  Star,
  StarFilled,
} from "@element-plus/icons-vue";
import api from "@/api";
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import defaultImage from "../assets/default-image.png";

const router = useRouter();
const userStore = useUserStore();

// 用户角色计算
const isTenant = computed(
  () => userStore.userInfo?.roles?.[0]?.name === "ROLE_Tenant"
);
const cityOptions = ref(["北京", "上海", "广州", "深圳"]);

// 收藏操作
const handleFavorite = async (houseId) => {
  try {
    const targetHouse = houses.value.find((h) => h.id === houseId);
    if (targetHouse) targetHouse.loading = true;
    const res = await api.collect.collectHouse(houseId, userStore.userInfo.id);
    const targetIndex = houses.value.findIndex((h) => h.id === houseId);
    if (targetIndex !== -1) {
      houses.value[targetIndex].isFavorite = res.data;
    }

    ElMessage.success(res.message);
  } catch (error) {
    ElMessage.error(error.response?.data?.message || "操作失败");
  } finally {
    const targetHouse = houses.value.find((h) => h.id === houseId);
    if (targetHouse) targetHouse.loading = false;
  }
};

// 分页和搜索相关逻辑
const houses = ref([]);
const sortField = ref("createTime");
const sortOrder = ref("desc");

const pagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 8,
});

const searchParams = reactive({
  city: "",
  rentType: "",
  title: "",
  minRent: null,
  maxRent: null,
});

// 获取房源数据
const fetchHouses = async () => {
  try {
    const params = {
      ...searchParams,
      status: 1,
      page: pagination.currentPage,
      size: pagination.pageSize,
      sortBy: sortField.value,
      order: sortOrder.value,
    };

    const res = await api.house.getHouses(params);

    const API_BASE = "http://localhost:8080";

    const processHouseImages = (house) => {
      const images = Array.isArray(house.houseImageList)
        ? house.houseImageList
        : [];

      return {
        ...house,
        houseImageList: images.map((img) => {
          if (!img) return defaultImage;

          const processedImg = img.startsWith("/") ? img.slice(1) : img;

          return img.startsWith("http") ? img : `${API_BASE}/${processedImg}`;
        }),
      };
    };

    if (userStore.isLoggedIn) {
      const collectStatus = await Promise.all(
        res.data.data.map((house) =>
          api.collect.checkCollectStatus(house.id, userStore.userInfo.id)
        )
      );

      houses.value = res.data.data.map((house, index) =>
        processHouseImages({
          ...house,
          isFavorite: collectStatus[index].data,
          loading: false,
        })
      );
    } else {
      houses.value = res.data.data.map(processHouseImages);
    }

    pagination.total = res.data.total;
  } catch (error) {
    console.error("房源加载失败:", error);
    ElMessage.error("数据加载失败");
  }
};

// 初始化加载
onMounted(async () => {
  await userStore.initialize();
  fetchHouses();
});

// 其他辅助方法
const handleSort = (field) => {
  sortField.value = field;
  sortOrder.value = sortOrder.value === "asc" ? "desc" : "asc";
  fetchHouses();
};

const handlePageChange = (page) => {
  pagination.currentPage = page;
  fetchHouses();
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchHouses();
};

const handleSearch = () => {
  pagination.currentPage = 1;
  fetchHouses();
};

const handleViewDetail = (houseId) => {
  router.push({
    path: `/houses/${houseId}`,
  });
};

const handleImageError = (event) => {
  console.error("图片加载失败:", event.target.src);
  event.target.src = defaultImage;
};
</script>

<style scoped>
.home-page {
  position: relative;
  min-height: 100vh;
}

.favorite-icon {
  color: #999;
  transition: all 0.3s;
  cursor: pointer;

  &.active {
    color: #ffd700;
  }

  &.loading {
    animation: rotate 1s linear infinite;
    opacity: 0.7;
    cursor: not-allowed;
  }

  &:hover:not(.loading) {
    transform: scale(1.1);
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 背景层样式 */
.hero-section {
  position: relative;
  height: 60vh;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: brightness(0.8);
}

/* 搜索容器 */
.search-container {
  position: relative;
  z-index: 2;
  padding-top: 30vh;
  max-width: 1200px;
  margin: 0 auto;
}

.btn-container {
  display: flex;
  padding: 8px 0;
  margin: auto;
}

.el-form-item__content {
  display: flex !important;
  justify-content: center !important;
}

.search-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.btn-wrapper {
  width: 100%;
  max-width: 200px; /* 控制最大宽度 */
}

.el-form {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

/* 房源列表区域 */
.house-list-section {
  padding: 40px 0;
  background: #f8f9fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 列表头部 */
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.section-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 20px;
}

.separator {
  color: #999;
  padding: 0 4px;
}

.search-container {
  padding: 20px 0;
}

.search-row {
  max-width: 1200px;
  margin: 0 auto;
}

.search-item {
  padding: 8px;
}

.el-input,
.el-select,
.rent-range {
  width: 100%;
}

.rent-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rent-input {
  flex: 1;

  :deep(.el-input__inner) {
    height: 40px;
    line-height: 40px;
  }
}

.total-count {
  font-size: 14px;
  color: #666;
}

/* 分页样式 */
.el-pagination {
  margin: 30px 0;
  justify-content: center;
}

/* 房源网格布局 */
.house-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin: 24px 0;
}

/* 房源卡片样式 */
.house-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  position: relative;
  cursor: pointer;
}

.house-card:hover {
  transform: translateY(-5px);
}

.house-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.image-placeholder {
  height: 200px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.card-content {
  padding: 16px;
  padding-bottom: 40px;
}

.favorite-button {
  pointer-events: auto;
  position: absolute;
  right: 16px;
  bottom: 16px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.1);
  }

  &:active {
    transform: scale(0.95);
  }
}

.house-title {
  font-size: 16px;
  color: #303133;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.house-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.house-info {
  font-size: 12px;
  color: #606266;
  line-height: 1.7;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-top: 12px;
}

.price {
  color: #e74c3c;
  font-size: 20px;
  font-weight: 600;
  margin-right: 4px;
}

.unit {
  color: #909399;
  font-size: 12px;
}

.status-tag {
  margin-left: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hero-section {
    height: 50vh;
  }

  .search-container {
    padding-top: 20vh;
  }

  .list-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .house-grid {
    grid-template-columns: 1fr;
  }

  .el-pagination {
    flex-wrap: wrap;
  }
}
</style>
